package com.dongqb.win;

import javax.swing.*;
import com.dongqb.bean.StockInfo;
import com.dongqb.common.CacheData;

import java.awt.*;
import java.awt.event.*;

public class MainWin {
	public JFrame frame;
	public JTextField textField;
	protected JList<StockInfo> jlist;
	public DefaultListModel<StockInfo> listModel;
	private TrayIcon trayIcon;
	private SystemTray systemTray;
	Font BlodFont = new Font("宋体", Font.BOLD, 12);
	Font msgFont = new Font("宋体", Font.PLAIN, 12);
	// 用于窗口拖拽的变量
	private int mouseX, mouseY;
	protected int checkIdx = -1;
	protected JPopupMenu suggestionPopup;
	public DefaultListModel<String> suggestionListModel;
	protected JList<String> suggestionList;
	protected JButton closeButton;
	/**
	 * @wbp.parser.entryPoint
	 */
	public MainWin() {
		initialize();
		try {
			createTrayIcon();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initialize() {

		frame = new JFrame();
		frame.setForeground(Color.DARK_GRAY);
		frame.setBackground(Color.DARK_GRAY);
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWin.class.getResource("/com/dongqb/exe/icon.png")));
		frame.setBounds(100, 100, 161, 500);
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.setUndecorated(true); // 取消原生标题栏
		frame.setType(Window.Type.UTILITY); // 关键设置，不显示在任务栏
		frame.setAlwaysOnTop(true);// 总置顶显示

		  // 获取屏幕尺寸
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
        Rectangle screenBounds = defaultScreen.getDefaultConfiguration().getBounds();
        
        // 计算右下角坐标
        int x = screenBounds.x + screenBounds.width - frame.getWidth()-20;
        int y = screenBounds.y + screenBounds.height - frame.getHeight()-60;
        
        // 设置窗口位置
        frame.setLocation(x, y);
        
		// 主面板使用BorderLayout
		JPanel mainPanel = new JPanel(new BorderLayout());
		frame.setContentPane(mainPanel);

		// 创建自定义标题栏
		JPanel titleBar = new JPanel(new BorderLayout());
		titleBar.setBackground(Color.BLACK);
		titleBar.setPreferredSize(new Dimension(frame.getWidth(), 30)); // 明确设置高度
		titleBar.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

		// 标题栏左侧图标
		JLabel iconLabel = new JLabel();
		try {
			ImageIcon icon = new ImageIcon(
					Toolkit.getDefaultToolkit().getImage(MainWin.class.getResource("/com/dongqb/exe/icon.png")));
			iconLabel.setIcon(new ImageIcon(icon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH)));
		} catch (Exception e) {
			// 加载失败时使用默认文本
			iconLabel.setText("LOGO");
			iconLabel.setForeground(Color.WHITE);
		}
		iconLabel.setOpaque(false);

		// 标题栏右侧关闭按钮
		closeButton = new JButton("×");
		closeButton.setVerticalAlignment(SwingConstants.TOP);
		closeButton.setHorizontalAlignment(SwingConstants.RIGHT);
		closeButton.setFont(new Font("Arial", Font.BOLD, 16));
		closeButton.setForeground(Color.WHITE);
		closeButton.setContentAreaFilled(false);
		closeButton.setBorderPainted(false);
		closeButton.setFocusPainted(false);
		// 鼠标悬停效果
		closeButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				closeButton.setForeground(Color.RED);
			}

			@Override
			public void mouseExited(MouseEvent e) {
				closeButton.setForeground(Color.WHITE);
			}
		});

		// 添加拖拽功能
		titleBar.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				mouseX = e.getX();
				mouseY = e.getY();
			}
		});

		titleBar.addMouseMotionListener(new MouseAdapter() {
			@Override
			public void mouseDragged(MouseEvent e) {
				frame.setLocation(e.getXOnScreen() - mouseX, e.getYOnScreen() - mouseY);
			}
		});

		// 将组件添加到标题栏
		JPanel leftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
		leftPanel.setOpaque(false);
		leftPanel.add(iconLabel);
		titleBar.add(leftPanel, BorderLayout.WEST);

		JLabel lblNewLabel = new JLabel("股票监控");
		lblNewLabel.setForeground(Color.LIGHT_GRAY);
		leftPanel.add(lblNewLabel);

		JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
		rightPanel.setOpaque(false);
		rightPanel.add(closeButton);
		titleBar.add(rightPanel, BorderLayout.EAST);

		// 添加标题栏到主面板
		mainPanel.add(titleBar, BorderLayout.NORTH);

		// 内容面板
		JPanel contentPanel = new JPanel(new BorderLayout());

		// 顶部输入框
		JPanel topPanel = new JPanel(new BorderLayout());
		topPanel.setBackground(Color.DARK_GRAY);
		topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		textField = new JTextField();
		textField.setForeground(Color.WHITE);
		textField.setBackground(Color.GRAY);
		topPanel.add(textField, BorderLayout.CENTER);
		contentPanel.add(topPanel, BorderLayout.NORTH);

		 // 初始化建议列表相关组件
	    suggestionListModel = new DefaultListModel<>();
	    suggestionList = new JList<>(suggestionListModel);
	    suggestionList.setBackground(Color.DARK_GRAY);
	    suggestionList.setForeground(Color.WHITE);
	    suggestionList.setSelectionBackground(new Color(50, 50, 50));
	    suggestionList.setSelectionForeground(Color.WHITE);
	    
	    suggestionPopup = new JPopupMenu();
	    suggestionPopup.setFocusable(false); // 关键：不主动获取焦点
	    suggestionPopup.setLightWeightPopupEnabled(true); // 使用轻量级弹出（推荐）
	    suggestionPopup.setBorder(BorderFactory.createLineBorder(Color.GRAY));
	    suggestionPopup.add(new JScrollPane(suggestionList));
	    
	    
		// 中间列表
		listModel = new DefaultListModel<StockInfo>();
		jlist = new JList<>(listModel);
		jlist.setCellRenderer(new StockItemRenderer());
		jlist.setBackground(Color.DARK_GRAY);
		jlist.setForeground(Color.WHITE);
		jlist.setSelectionBackground(new Color(50, 50, 50));
		jlist.setSelectionForeground(Color.WHITE);
		jlist.setFixedCellHeight(50); // 匹配渲染器的高度
		JScrollPane scrollPane = new JScrollPane(jlist);
		contentPanel.add(scrollPane, BorderLayout.CENTER);

		// 将内容面板添加到主面板
		mainPanel.add(contentPanel, BorderLayout.CENTER);
	}

	@SuppressWarnings("deprecation")
	private void createTrayIcon() throws Exception {
		if (!SystemTray.isSupported()) {
			System.out.println("SystemTray is not supported");
			return;
		}

		systemTray = SystemTray.getSystemTray();
		Image image = Toolkit.getDefaultToolkit().getImage(MainWin.class.getResource("/com/dongqb/exe/icon.png"));

		// 创建弹出菜单
		PopupMenu popup = new PopupMenu();

		MenuItem showItem = new MenuItem("显示窗口");
		showItem.setFont(msgFont);
		showItem.addActionListener(e -> frame.setVisible(true));

		MenuItem exitItem = new MenuItem("退出");
		exitItem.setFont(msgFont);
		exitItem.addActionListener(e -> {
			CacheData.onTimeService.stop();
			systemTray.remove(trayIcon);
			System.exit(0);
		});

		popup.add(showItem);
		popup.addSeparator();
		popup.add(exitItem);

		trayIcon = new TrayIcon(image, "股票监控", popup);
		trayIcon.setImageAutoSize(true);

		// 双击图标显示窗口
		trayIcon.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					frame.setVisible(true);
				}
			}
		});

		try {
			systemTray.add(trayIcon);
		} catch (AWTException e) {
			System.err.println("TrayIcon could not be added.");
		}
	}

	// 自定义列表项渲染器 - 使用绝对布局
	class StockItemRenderer extends JPanel implements ListCellRenderer<StockInfo> {
		private static final long serialVersionUID = 1L;
		private JLabel nameLabel;
		private JLabel codeLabel;
		private JLabel priceLabel;
		private JLabel riseLabel;
		private Image backgroundImage;

		public StockItemRenderer() {
			setLayout(null); // 关键！启用绝对布局
			setOpaque(true);

			// 1. 股票名称标签 (左对齐)
			nameLabel = new JLabel();
			nameLabel.setBackground(Color.PINK);
			nameLabel.setBounds(10, 5, 50, 15);
			nameLabel.setFont(msgFont);
			nameLabel.setForeground(Color.WHITE);
			add(nameLabel);
			
			//2股票编号
			codeLabel = new JLabel();
			codeLabel.setBackground(Color.PINK);
			codeLabel.setBounds(75, 5, 50, 15);
			codeLabel.setFont(msgFont);
			codeLabel.setForeground(Color.WHITE);
			add(codeLabel);

			// 3. 涨跌幅标签 (右对齐)
			priceLabel = new JLabel();
			priceLabel.setForeground(Color.WHITE);
			priceLabel.setBounds(10, 30, 50, 15);
			priceLabel.setFont(msgFont);
			add(priceLabel);
			
			//4涨跌
			riseLabel = new JLabel();
			riseLabel.setBackground(Color.PINK);
			riseLabel.setBounds(75, 30, 50, 15);
			riseLabel.setFont(BlodFont);
			riseLabel.setForeground(Color.WHITE);
			add(riseLabel);

		}

		@Override
		public Component getListCellRendererComponent(JList<? extends StockInfo> list, StockInfo value, int index,
				boolean isSelected, boolean cellHasFocus) {
			if(value.getZd()==null) {
				value.setZd("+0.0%");
			}
			if(value.getXj()==null) {
				value.setXj("--");
			}
			// 设置文本
			nameLabel.setText(value.getMc());
			codeLabel.setText(value.getBh());
			priceLabel.setText(value.getXj());
			riseLabel.setText(value.getZd());
			// 涨跌颜色
			if (value.getZd().startsWith("+")) {
				// 背景色设置
				if (isSelected) {
					backgroundImage = new ImageIcon(MainWin.class.getResource("/com/dongqb/exe/bg_ck_red.png"))
							.getImage();
				} else {
					backgroundImage = new ImageIcon(MainWin.class.getResource("/com/dongqb/exe/bg_no_red.png"))
							.getImage();
				}
			} else {
				if (isSelected) {
					backgroundImage = new ImageIcon(MainWin.class.getResource("/com/dongqb/exe/bg_ck_green.png"))
							.getImage();
				} else {
					backgroundImage = new ImageIcon(MainWin.class.getResource("/com/dongqb/exe/bg_no_green.png"))
							.getImage();
				}
			}

			return this;
		}

		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			if (backgroundImage != null) {
				// 绘制背景图片，缩放以适应面板大小
				g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
			}
		}
	}

}
